package com.kgc.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kgc.server.dao.*;
import com.kgc.server.pojo.*;
import com.kgc.server.service.OrderService;
import com.kgc.server.util.Page;
import com.kgc.server.util.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private EasybuyOrderDao easybuyOrderDao;

    @Autowired
    private BuyCarDao buyCarDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private EasybuyOrderDetailDao easybuyOrderDetailDao;

    @Override
    public ResponseMessage addOrder(String userId) {
        logger.info("OrderServiceImpl addOrder userId:" + userId);
        ResponseMessage msg = new ResponseMessage();
        try {
            //获取购物车用户的购物车
            List<EasybuyCar> easybuyCars = buyCarDao.selectUserCar(userId);
            //获取购物车的详细信息
            List<EasybuyProduct> easybuyProductList = new ArrayList<EasybuyProduct>();
            for (EasybuyCar easybuyCar : easybuyCars) {
                String productId = easybuyCar.getProductId();
                easybuyProductList.add(productDao.getProductById(productId));
            }
            //计算总价格
            BigDecimal sum = new BigDecimal("0");
            for (EasybuyProduct easybuyProduct : easybuyProductList) {
                for (EasybuyCar easybuyCar : easybuyCars) {
                    if (easybuyProduct.getId().equals(easybuyCar.getProductId())) {
                        BigDecimal size = new BigDecimal(easybuyCar.getProductNum());
                        BigDecimal price = new BigDecimal(easybuyProduct.getPrice());
                        BigDecimal a = price.multiply(size);
                        sum = a.add(sum);
                        easybuyProduct.setStock(easybuyProduct.getStock() - easybuyCar.getProductNum());
                        productDao.modifyProductStock(Integer.parseInt(easybuyProduct.getId()),easybuyProduct.getStock());
                    }

                }
            }
            //查询用户的默认地址
            Address address = addressDao.selectDefaultAddress(userId);
            //随机编号
            String sNumber = UUID.randomUUID().toString();
            //生成订单
            EasybuyOrder easybuyOrder = new EasybuyOrder();
            easybuyOrder.setCost(sum);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            easybuyOrder.setCreateTime(sdf.format(new Date()));
            easybuyOrder.setSerialNumber(sNumber);
            easybuyOrder.setLoginName(address.getUserName());
            easybuyOrder.setUserAddress(address.getAddress());
            easybuyOrder.setUserId(userId);
            int i = easybuyOrderDao.addOrder(easybuyOrder);
            logger.info("OrderServiceImpl addOrder userId:" + userId + ";result:" + i);
            EasybuyOrder easybuyOrder1 = easybuyOrderDao.getOrderBySerialNumber(sNumber);
            for (EasybuyProduct easybuyProduct : easybuyProductList) {
                for (EasybuyCar easybuyCar : easybuyCars) {
                    if (easybuyProduct.getId().equals(easybuyCar.getProductId())) {
                        EasybuyOrderDetail easybuyOrderDetail = new EasybuyOrderDetail();
                        easybuyOrderDetail.setOrderId(easybuyOrder1.getId());
                        easybuyOrderDetail.setQuantity(easybuyCar.getProductNum().toString());
                        easybuyOrderDetail.setProductId(easybuyCar.getProductId());
                        BigDecimal productNum = new BigDecimal(easybuyCar.getProductNum());
                        BigDecimal price = new BigDecimal(easybuyProduct.getPrice());
                        easybuyOrderDetail.setCost(price.multiply(productNum));
                        //添加订单详情
                        easybuyOrderDetailDao.addDetail(easybuyOrderDetail);
                    }
                    int i1 = buyCarDao.deleteCarById(easybuyCar.getId());
                }


            }
            msg.setMsg("添加订单成功！");
            msg.setCode("200");
            msg.setData(sNumber);
        } catch (Exception e) {
            logger.error("OrderServiceImpl addOrder error userId:" + userId, e);
            e.printStackTrace();
        }
        return msg;
    }

    @Override
    public ResponseMessage getOrderBySerialNumber(String s) {
        logger.info("OrderServiceImpl getOrderBySerialNumber params: s:"+s);
        ResponseMessage msg = new ResponseMessage();
        EasybuyOrder orderBySerialNumber = easybuyOrderDao.getOrderBySerialNumber(s);
        msg.setData(orderBySerialNumber);
        msg.setCode("200");
        msg.setMsg("查询成功");
        return msg;
    }

    @Override
    public ResponseMessage getOrdersByUserId(String userId, String serialNumber,Integer pageNo) {
        logger.info("OrderServiceImpl getOrdersByUserId params: userId:"+userId+";serialNumber:"+serialNumber);
        ResponseMessage msg = new ResponseMessage();
        Page page = new Page();
        PageHelper.startPage(pageNo,6);
        List<EasybuyOrder> orders = easybuyOrderDao.getOrdersByUserId(userId, serialNumber);
        logger.info("OrderServiceImpl getOrdersByUserId params: userId:"+userId+";serialNumber:"+serialNumber+";result:"+orders);
        PageInfo<EasybuyOrder> pageInfo = new PageInfo<>(orders);
        page.setPageNo(pageNo);
        page.setPageCount(pageInfo.getNavigateLastPage());
        page.setPageSize(pageInfo.getPageSize());
        page.setList(pageInfo.getList());
        page.setCount(easybuyOrderDao.getOrdersByUserId(userId,serialNumber).size());
        msg.setData(page);
        msg.setCode("200");
        msg.setMsg("查询成功！");


        return msg;
    }

    public ResponseMessage getOAndP(String oId){
        logger.info("ResponseMessage getOAndP(String oId:"+oId+")");
        ResponseMessage msg=new ResponseMessage();
        List<EasybuyOrderDetail> oAndP = easybuyOrderDao.getOAndP(oId);
        msg.setCode("200");
        msg.setData(oAndP);
        logger.info("ResponseMessage getOAndP(String oId:"+oId+")msg:"+msg);
        return msg;
    }

}
